/*
 *	settings-view view
 *  -----------------------------------------------------------------------------------------------------------
 */

site.view('messages-view', {
	
	onLoad: function(settings) {
		this.startAll(settings);
	},
	
	onUnload: function() {
		this.stopAll();
	}
})

/*
 *	settings main view manager (internal navigation) module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('main_view_manager', function(context) {
	var query = context.query,
		request	= context.request,
		require = context.require,
		tipsy = require('tipsy'),
		livequery = require('livequery'),

		processing = false,
		contentContainer,
		internalActions,
		rLastUrlPart = /[^\/]*$/,
		currentModuleView = '',

		onMenuClick = function(e) {
			var anchor = $(this),
	       		action = anchor.attr('href'),
	       		old_content_height = contentContainer.innerHeight(),
	       	 	old_content = contentContainer.children('div'),
	       	 	urlName = anchor.find('.mini_name').text(),

	       	 	actionName = action.substring(action.indexOf('message'))
								   .replace('message/', '')
								   .replace('message', '')
								   .split('/');
       
			if (!$(this).children('div').hasClass('active') && !processing) {
				processing = true;

				$('#content > aside .list_main_container').removeClass('active');
				$(this).children('div').addClass('active');

				request({
				    url: action,
				    dataType: 'json',
				    cache: false,
				    success: function(json) {             
				        contentContainer.css({'height':old_content_height + 'px',
				                               'overflow':'hidden'});

				        var new_content = old_content.after(json.content).next('div'),              
				       		new_content_height = new_content.innerHeight(),
				        	animation_time = 700;
				        
				        old_content.children('.header_menu')
				                   .css('position','relative')
				                   .next('div')
				                   .css('padding-top','0px');
				      
				       	// Load new view module (and inform about change) 
				        context.trigger(currentModuleView[0] + 'ViewUnloaded', currentModuleView.slice(1));
				        context.trigger(actionName[0] + 'ViewLoaded', actionName.slice(1));
				        currentModuleView = actionName;
				        
				        old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function() {
    
				            $(this).remove();
				        });

				        contentContainer.animate({'height': new_content_height + 'px'},animation_time,function() {
				            $('#content > section').css('height','auto')
				                                    .children('div')
				                                    .children('.header_menu')
				                                    .css('position','absolute')
				                                    .next('div')
				                                    .css('padding-top','47px');

				            processing = false;
				            window.history.pushState(urlName, urlName, anchor.attr('href'));
				        });   

				        return false;     
				    }
				});      
			}
       		e.preventDefault();
       		return false;
    
		};

	return {

		init: function(settings) {
			contentContainer = query('#content > section');
			internalActions = query('.internal_action');

			internalActions.on('click', onMenuClick);

			// init default view (from url)
			
			var href = document.location.href;
			currentModuleView = href.substring(href.indexOf('message'))
									.replace('message/', '')
									.replace('message', '')
									.split('/');

			currentModuleView = currentModuleView[0] !== '' ? currentModuleView : ['desktop'] ;
			context.trigger(currentModuleView[0] + 'ViewLoaded', currentModuleView.slice(1));

			// tipsy forms		
			livequery.init('input, textarea', function() {
				tipsy.init(this, {
					gravity: query(window).width() < 1260 ? 's' : 'w',
					trigger: 'focus'
				})
			});

			// tipsy actions
			livequery.init('.tooltip', function(){
        		this.tipsy({gravity:'se'});
    		});		
		},

		destroy: function() {
			internalActions.off(onMenuClick);
		}

	}

})

/*
 *	write message view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('write_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		autocomplete = require('autocomplete'),
		notify = require('notify');
	
	return {
		events: {

			writeViewLoaded: function(subView) {
				console.log('write loaded');

				// send messsage form
				ajaxSubmitForm.init('.standard_form',{

					mapInputFields: {
						'recipient': 'textboxlist'
					},

					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });  
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					}
				});

				// autocomplete place init
				var textboxlist = autocomplete.init('#recipient', {
					url: '/contact/get_contacts',
					max: 5,
					method: 'binary',
					minLength: 1,
					onlyFromValues: true
				});

				request({
				 	url: '/contact/get_contacts', 
                  	dataType: 'json',
                  	success: function(data){
                      	textboxlist.plugins['autocomplete'].setValues(data);
                    }  
                
                },true);
			},

			writeViewUnloaded: function(subView) {
				console.log('write unloaded');
				ajaxSubmitForm.destroy('.standard_form');
			}
		}
	}
})

/*
 *	inbox message view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('inbox_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		actionDialog = require('actionDialog');
	
	return {
		events: {

			inboxViewLoaded: function(subView) {
				console.log('inbox loaded');

				$('#content .btn_answer').on('click', function(e) {
					$(this).next('form.standard_form').toggle();
					$(this).remove();
					e.preventDefault();
				});

				// ajax submit form init (send message from inbox)
				ajaxSubmitForm.init('.standard_form',{

					success: function(data) {
						notify.create("create", {
                        	title: data.message,
                            text: data.description
                        });
					},

					error: function(data) {
						var err_msg = '';
						
						util.eachRecursive(data.errors, function(key, val) {
							err_msg += err_msg === '' ? val : '<br/>' + val;
						});
						
						notify.create('create','error-template', {
							title: data.message,
							text: err_msg
						});
					},

					getSuffixVal: function() {
						var el = this.find('input[name=inbox_id]');

						if(el.length > 0) {
							return '_' + el.val();
						} else {
							return '';
						}
					}
				});

				// delete action
				actionDialog.create('.delete', function(el) {
					var anchor = el,
			        	action = anchor.attr('href');
			        
			        request({
			            url: action,
			            dataType: 'json',
			            success: function(json) {
			                anchor.parents('li').slideUp('fast', function() {
			                	$(this).remove();
			                })
			            }
			        });
				});
			},

			inboxViewUnloaded: function() {
				console.log('inbox unloaded');
				ajaxSubmitForm.destroy('.standard_form');
			},

			messageShow: function(container, action, visible) {

				if (visible && container.hasClass('unread')) {
		            request({
		                url: action,
		                dataType: 'json',
		                cache: false,
		                success: function(data) { 
		                    container.removeClass('unread')
		                }
		            });
		        }
			}
		}
	}
})

/*
 *	outbox message view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('outbox_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		actionDialog = require('actionDialog');
	
	return {
		events: {

			outboxViewLoaded: function(subView) {
				console.log('outbox loaded');

				// delete action
				actionDialog.create('.delete', function(el) {
					var anchor = el,
			        	action = anchor.attr('href');
			        
			        request({
			            url: action,
			            dataType: 'json',
			            success: function(data) {
			                anchor.parents('li').slideUp('fast', function() {
			                	$(this).remove();
			                })
			            }
			        });
				});
			}
		}
	}
})

/*
 *	bin message view module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('bin_view', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util,
		ajaxSubmitForm = require('ajaxSubmitForm'),
		notify = require('notify'),
		actionDialog = require('actionDialog');
	
	return {
		events: {

			binViewLoaded: function(subView) {
				console.log('bin loaded');

				// delete action
				actionDialog.create('.delete', function(el) {
					var anchor = el,
			        	action = anchor.attr('href');
			        
			        request({
			            url: action,
			            dataType: 'json',
			            success: function(json) {
			                anchor.parents('li').slideUp('fast', function() {
			                	$(this).remove();
			                })
			            }
			        });
				});
			}
		}
	}
})

/*
 *	slide up/down message module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('slide_message', function(context) {
	var query = $ = context.query,
		request	= context.request,
		require = context.require,
		util = context.util;
	
	return {
		init: function(settings) {
			
			$('#content').on('click', 'section ul > li .message_link', function(e) {
				var action = $(this).attr('href'), 
      				container = $(this).parents('.list_main_container'),
					all_message_link = $('#content > section ul > li .message_link'),
		        	all_active = all_message_link.parents('.active');          
		        
		        all_active.next('div').hide();

		        if (container.hasClass('active')) {
		            container.removeClass('active').next('div').hide();
		            context.trigger('messageShow', container, action, false);
		        } else {
		            all_active.removeClass('active')
		            container.addClass('active').next('div').show();
		            context.trigger('messageShow', container, action, true);
		        }

		        e.preventDefault();
			});
		}
	}
})


/*
 *	messages pagination module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('messages_pagination', function(context) {

	var query = $ = context.query,
		require = context.require,
		request = context.request,
		util = context.util,
		processing = false,
		animation_time = 700,
		content_container,

		onPagination = function(e) {
		
			if(processing) {
				e.preventDefault();
				return false;
			}

			var content_container = $('#content > section > div'),
				action = $(this).attr('href'),   
				header = $(this).parents('header'),
             	old_content = content_container.children('div'),
				old_content_height = old_content.innerHeight();

			processing = true;

            request({
                url: action,
                dataType: 'json',
                type: 'post',
                data: { internal_pagination: 1},
                cache: false,
                success: function(data) { 

                	if(data.success !== true) {
                		processing = false;
                		return;
                	}

                    content_container.css({'height':old_content_height + 47 + 'px',
                                           'overflow':'hidden'});

                    $('.pagination').remove();
                    header.append(data.pagination);
                    $('.pagination > .button_header').click(function(event){event.preventDefault()});    

                    var new_content = old_content.after(data.content).next('div'),               
                    	new_content_height = new_content.innerHeight();

                    old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function() {
                        $(this).remove();
                    });

                    content_container.animate({'height': new_content_height + 47 + 'px'},animation_time,function() {
                        $('#content > section > div').css('height','auto');
                        processing = false;
                    });  

                },

                error: function() {
                	processing = false;
                }
            });

			e.preventDefault();
			return false;
		};

	return {
		init: function(settings) {
			$('#content').on('click', '.pagination > .button_header', onPagination);
		}
	}
})

/*
 *	searchbox module
 *  -----------------------------------------------------------------------------------------------------------
 */ 

.module('search_box', function(context) {

	var query = $ = context.query,
		require = context.require,
		request = context.request,
		util = context.util,
		processing = false,
		animation_time = 700,
		content_container,

		onSearch = function(e) {
		
			if(processing) {
				e.preventDefault();
				return false;
			}

			var content_container = $('#content > section > div'),
				action = $(this).attr('action'),   
				header = $(this).parents('header'),
             	old_content = content_container.children('div'),
				old_content_height = old_content.innerHeight();

			processing = true;

            request({
                url: action,
                dataType: 'json',
                type: 'get',
                data: $(this).serialize({checkboxesAsBools: true}),
                cache: false,
                success: function(data) { 

                	if(data.success !== true) {
                		processing = false;
                		return;
                	}

                    content_container.css({'height':old_content_height + 47 + 'px',
                                           'overflow':'hidden'});

                     $('.pagination').remove();
                     header.append(data.pagination);
                     $('.pagination > .button_header').click(function(event){event.preventDefault()});    

                    var new_content = old_content.after(data.content).next('div'),               
                    	new_content_height = new_content.innerHeight();

                    old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function() {
                        $(this).remove();
                    });

                    content_container.animate({'height': new_content_height + 47 + 'px'},animation_time,function() {
                        $('#content > section > div').css('height','auto');
                        processing = false;
                    });  

                },

                error: function() {
                	processing = false;
                }
            });

			e.preventDefault();
			return false;
		};

	return {
		init: function(settings) {
			$('#content').on('submit', '#message_search_form', onSearch);
		}
	}
})